<template>
  <div class="book-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>图书管理系统</span>
          <el-button type="primary" @click="showAddDialog">添加图书</el-button>
        </div>
      </template>
      
      <!-- 图书列表 -->
      <el-table :data="books" style="width: 100%" v-loading="loading">
        <el-table-column prop="bookname" label="书名" />
        <el-table-column prop="author" label="作者" />
        <el-table-column prop="publisher" label="出版社" />
        <el-table-column prop="publishDate" label="出版日期">
          <template #default="scope">
            {{ formatDate(scope.row.publishDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格">
          <template #default="scope">
            ¥{{ scope.row.price?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="num" label="库存数量" width="100" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="success" 
              @click="handleBorrow(scope.row)"
              :disabled="scope.row.num <= 0"
            >
              借阅
            </el-button>
            <el-button 
              size="small" 
              type="warning" 
              @click="handleReturn(scope.row)"
              :disabled="scope.row.num > 0"
            >
              归还
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑图书对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="bookForm" label-width="100px">
        <el-form-item label="书名">
          <el-input v-model="bookForm.bookname" />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="bookForm.author" />
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="bookForm.publisher" />
        </el-form-item>
        <el-form-item label="出版日期">
          <el-date-picker
            v-model="bookForm.publishDate"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number 
            v-model="bookForm.price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
          />
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input-number 
            v-model="bookForm.num" 
            :min="0" 
            :precision="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 公告弹窗 -->
    <el-dialog
      v-model="noticeDialogVisible"
      title="系统公告"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="notice-content">
        <p>{{ latestNotice?.content }}</p>
        <div class="notice-time">{{ formatDate(latestNotice?.publishdate) }}</div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeNotice">我知道了</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { getAllNotices } from '../api/notice'

const books = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加图书')
const latestNotice = ref(null)
const noticeDialogVisible = ref(false)
const bookForm = ref({
  bookid: null,
  bookname: '',
  author: '',
  publisher: '',
  publishDate: '',
  price: 0,
  num: 0
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取所有图书
const fetchBooks = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/books')
    books.value = response.data
  } catch (error) {
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 获取最新公告
const fetchLatestNotice = async () => {
  try {
    const res = await getAllNotices()
    if (res.code === 200 && res.data.length > 0) {
      // 按发布时间倒序排序，获取最新的一条
      const sortedNotices = res.data.sort((a, b) => 
        new Date(b.publishdate) - new Date(a.publishdate)
      )
      latestNotice.value = sortedNotices[0]
      noticeDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取公告失败:', error)
  }
}

// 关闭公告
const closeNotice = () => {
  noticeDialogVisible.value = false
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加图书'
  bookForm.value = {
    bookid: null,
    bookname: '',
    author: '',
    publisher: '',
    publishDate: '',
    price: 0,
    num: 0
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑图书'
  bookForm.value = { ...row }
  dialogVisible.value = true
}

// 提交表单（添加/编辑）
const handleSubmit = async () => {
  try {
    if (bookForm.value.bookid) {
      // 编辑
      await axios.put(`/api/books/${bookForm.value.bookid}`, bookForm.value)
      ElMessage.success('更新成功')
    } else {
      // 添加
      await axios.post('/api/books', bookForm.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchBooks()
  } catch (error) {
    ElMessage.error(bookForm.value.bookid ? '更新失败' : '添加失败')
  }
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await axios.delete(`/api/books/${row.bookid}`)
    ElMessage.success('删除成功')
    fetchBooks()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 处理借阅
const handleBorrow = async (row) => {
  try {
    await axios.post(`/api/books/${row.bookid}/borrow`)
    ElMessage.success('借阅成功')
    fetchBooks()
  } catch (error) {
    ElMessage.error('借阅失败')
  }
}

// 处理归还
const handleReturn = async (row) => {
  try {
    await axios.post(`/api/books/${row.bookid}/return`)
    ElMessage.success('归还成功')
    fetchBooks()
  } catch (error) {
    ElMessage.error('归还失败')
  }
}

onMounted(() => {
  fetchBooks()
  fetchLatestNotice()
})
</script>

<style scoped>
.book-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.notice-content {
  padding: 20px;
  text-align: center;
}

.notice-time {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
  text-align: right;
}
</style> 